#include <gtest/gtest.h>
#include <sys/epoll.h>
#include <unistd.h>
#include <vector>
#include <fcntl.h>

#include "epoll_poller.h"  // 你的 EpollPoller 类头文件
#include "channel.h"       // 你的 Channel 类头文件

TEST(EpollPollerTest, CreateAndDestroy) {
    EpollPoller poller;
    ASSERT_GT(poller.getEpollFd(), 0);
}

TEST(EpollPollerTest, AddModifyRemoveChannel) {
    EpollPoller poller;

    int fds[2];
    pipe(fds);  // 创建一对管道 fd，作为模拟 fd

    Channel channelRead(fds[0]);
    channelRead.set_events(EPOLLIN);

    // 初次添加
    poller.updateChannel(&channelRead);

    // 修改事件
    channelRead.set_events(EPOLLIN | EPOLLOUT);
    poller.updateChannel(&channelRead);

    // 删除
    poller.removeChannel(&channelRead);

    close(fds[0]);
    close(fds[1]);
}

TEST(EpollPollerTest, PollActiveChannels) {
    EpollPoller poller;

    int fds[2];
    pipe(fds);
    int flags = fcntl(fds[0], F_GETFL, 0);
    fcntl(fds[0], F_SETFL, flags | O_NONBLOCK);

    Channel channelRead(fds[0]);
    channelRead.set_events(EPOLLIN);
    poller.updateChannel(&channelRead);
    std::cout << "MockChannel events: " << channelRead.events() << std::endl;

    // 让 fds[1] 写数据，fds[0] 会有可读事件
    const char* msg = "test";
    ssize_t n = write(fds[1], msg, 4);
    ASSERT_EQ(n, 4) << "写入管道失败";

    std::vector<Channel*> activeChannels;
    poller.poll(1000, activeChannels);

    ASSERT_FALSE(activeChannels.empty());
    ASSERT_EQ(activeChannels[0]->fd(), fds[0]);

    poller.removeChannel(&channelRead);
    close(fds[0]);
    close(fds[1]);
}

